//
//  HomeAddressVC.m
//  jinwang
//
//  Created by jzb on 2018/3/7.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "HomeAddressVC.h"
#import "BRAddressPickerView.h"

@interface HomeAddressVC ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    
    UIButton *shiquBut;
    UITextView *xiangxiTextView;
    
    NSString *_homeAddStr;
    NSString *_homeAddStrID;
    NSString *string1;
    NSString *string2;
    NSString *string3;
}
@property (nonatomic,strong) UIButton *preserveBtn;
@property (nonatomic,strong) NSString *HomeAddress;

@property (nonatomic,strong) NSArray *addressArr; // 解析出来的最外层数组
@property (nonatomic,strong) NSArray *provinceArr; // 省
@property (nonatomic,strong) NSArray *countryArr; // 市
@property (nonatomic,strong) NSArray *districtArr; // 区
@property (nonatomic,strong) NSArray *districtIDArr; // 区
@property (nonatomic,assign) NSInteger index1; // 省下标
@property (nonatomic,assign) NSInteger index2; // 市下标
@property (nonatomic,assign) NSInteger index3; // 区下标



@end

@implementation HomeAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"家庭住址";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *preserveItem = [[UIBarButtonItem alloc]initWithCustomView:self.preserveBtn];
    self.navigationItem.rightBarButtonItem = preserveItem;
    
    if (self.selections.count) {
        self.index1 = [self.selections[0] integerValue];
        self.index2 = [self.selections[1] integerValue];
        self.index3 = [self.selections[2] integerValue];
    }
    [self AddressJsonRequest];

}
- (void)HomeAddressViewBuild{
    
    UIView *addressBG = [[UIView alloc]initWithFrame:CGRM(0, 128, 750, 240)];
    
    [self.view addSubview:addressBG];
    UILabel *shiquLabel = [[UILabel alloc]initWithFrame:CGRM(20, 40, 140, 40)];
    
    shiquLabel.text = @"省市区：";
    
    [addressBG addSubview:shiquLabel];
    
    shiquBut = [[UIButton alloc]initWithFrame:CGRM(160, 0, 750-160-70, 119)];
    
    shiquBut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [shiquBut setTitleColor:kRGBColor(90, 90, 90) forState:UIControlStateNormal];
    
    [shiquBut addTarget:self action:@selector(HomeAddressBuild:) forControlEvents:UIControlEventTouchUpInside];
    
    [addressBG addSubview:shiquBut];
    
    UIImageView *shiquImg = [[UIImageView alloc]initWithFrame:CGRM(750-60, 40, 20, 40)];
    
    shiquImg.image = [UIImage imageNamed:@"jw_find_rightJT"];
    
    [addressBG addSubview:shiquImg];
    
    UIView *shiquLine = [[UIView alloc]initWithFrame:CGRM(0, 120, 750, 1)];
    
    shiquLine.backgroundColor = [UIColor lightGrayColor];
    
    [addressBG addSubview:shiquLine];
    
    UILabel *xiangxiLabel = [[UILabel alloc]initWithFrame:CGRM(20, 160, 180, 40)];
    
    xiangxiLabel.text = @"详细地址：";
    
    [addressBG addSubview:xiangxiLabel];
    
    xiangxiTextView = [[UITextView alloc]initWithFrame:CGRM(180, 143, 750-200, 70)];
    
    xiangxiTextView.font = [UIFont systemFontOfSize:17];
    
    [addressBG addSubview:xiangxiTextView];
    
    UIView *xiangxiLine = [[UIView alloc]initWithFrame:CGRM(0, 239, 750, 1)];
    
    xiangxiLine.backgroundColor = [UIColor lightGrayColor];
    
    [addressBG addSubview:xiangxiLine];
    
    [self HomeAddressBuild:shiquBut];
    
}
#pragma mark -懒加载
- (UIButton *)preserveBtn{
    if (!_preserveBtn) {
        _preserveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _preserveBtn.frame = CGRectMake(0, 0, 44, 44);
        [_preserveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_preserveBtn addTarget:self action:@selector(preserveButOnclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _preserveBtn;
}
- (NSArray *)provinceArr
{
    if (_provinceArr == nil) {
        _provinceArr = [[NSArray alloc] init];
    }
    return _provinceArr;
}
-(NSArray *)countryArr
{
    if(_countryArr == nil)
    {
        _countryArr = [[NSArray alloc] init];
    }
    return _countryArr;
}

- (NSArray *)districtArr
{
    if (_districtArr == nil) {
        _districtArr = [[NSArray alloc] init];
    }
    return _districtArr;
}

-(NSArray *)addressArr
{
    if (_addressArr == nil) {
        _addressArr = [[NSArray alloc] init];
    }
    return _addressArr;
}

- (void)HomeAddressBuild:(UIButton *)sender{
    
//    BRAddressPickerVie
    
//    [BRAddressPickerView showAddressPickerWithDefaultSelected:nil isAutoSelect:YES resultBlock:^(NSArray *selectAddressArr) {
//
//        NSLog(@"-=-=-=>>%@",selectAddressArr);
//
//        [sender setTitle:[NSString stringWithFormat:@"%@-%@-%@",selectAddressArr[0],selectAddressArr[1],selectAddressArr[2]] forState:UIControlStateNormal];
//
//        _homeAddStr = [NSString stringWithFormat:@"%@-%@-%@",selectAddressArr[0],selectAddressArr[1],selectAddressArr[2]];
//    }];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRM(0, 940, 750, 2)];
    lineView.backgroundColor = kRGBColor(240, 240, 240);
    [self.view addSubview:lineView];
    UIPickerView *HomeAddpickView = [[UIPickerView alloc]initWithFrame:CGRM(0, 942, 750, 392)];
    
    [HomeAddpickView selectRow:0 inComponent:0 animated:YES];
    
    HomeAddpickView.delegate = self;
    HomeAddpickView.dataSource = self;
//    HomeAddpickView.backgroundColor = kRGBColor(240, 240, 240);
    
    [self.view addSubview:HomeAddpickView];
    
}
- (void)loadFirstData
{
   
    NSMutableArray *firstName = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in self.addressArr)
    {
        NSString *name = [dict objectForKey:@"short_name"];
        [firstName addObject:name];
    }
    // 第一层是省份 分解出整个省份数组
    self.provinceArr = firstName;
}
// 根据传进来的下标数组计算对应的三个数组
- (void)calculateFirstData
{
    // 拿出省的数组
    [self loadFirstData];
    
    NSMutableArray *cityNameArr = [[NSMutableArray alloc] init];
    // 根据省的index1，默认是0，拿出对应省下面的市
    NSDictionary *cityDic = self.addressArr[self.index1];
    NSArray *cityArr = [cityDic objectForKey:@"children"];
    for (NSDictionary *cityName in cityArr) {
        
        NSString *name1 = [cityName objectForKey:@"short_name"];
        [cityNameArr addObject:name1];
    }
    // 组装对应省下面的市
    NSMutableArray *districtNameArr = [[NSMutableArray alloc] init];
    NSMutableArray *districtIDArr = [[NSMutableArray alloc] init];
    self.countryArr = cityNameArr;
    NSDictionary *districtDic = cityArr[self.index2];
    NSArray *districtArr001 = [districtDic objectForKey:@"children"];
    for (NSDictionary *istrictName in districtArr001) {
        
        NSString *name1 = [istrictName objectForKey:@"short_name"];
        NSString *districtID = [NSString stringWithFormat:@"%@",[istrictName objectForKey:@"region_id"]];
        [districtNameArr addObject:name1];
        [districtIDArr addObject:districtID];
    }
    //                             index1对应省的字典         市的数组 index2市的字典   对应市的数组
    // 这里的allValue是取出来的大数组，取第0个就是需要的内容
    self.districtArr = districtNameArr;
    self.districtIDArr = districtIDArr;
}
#pragma mark - UIPickerViewDataSource Implementation
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // Returns
    switch (component)
    {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        case 2:return self.districtArr.count;
        default:break;
    }
    return 0;
}
#pragma mark UIPickerViewDelegate Implementation


- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0: return self.provinceArr[row];break;
        case 1: return self.countryArr[row];break;
        case 2:return self.districtArr[row];break;
        default:break;
    }
    return nil;
}
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *titleString;
    
    if (component == 0) {
 
        titleString = self.provinceArr[row];
    }
    else if (component == 1){

        titleString = self.countryArr[row];
        
    }
    else if (component == 2){

        titleString = self.districtArr[row];
        
    }
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:titleString];
    NSRange range = [titleString rangeOfString:titleString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xEEA72B) range:range];
    
    return attributedString;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    //设置分割线的颜色
    for(UIView *singleLine in pickerView.subviews)
    {
        if (singleLine.frame.size.height < 1)
        {
            singleLine.backgroundColor = UIColorHex(0xEEA72B);
        }
    }
    UILabel* label = (UILabel*)view;
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:17]];
        label.textColor = kRGBColor(80, 80, 80);
        label.adjustsFontSizeToFitWidth = YES;
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setBackgroundColor:[UIColor clearColor]];
    }
    
    NSString * title = @"";
    switch (component)
    {
        case 0: title =   self.provinceArr[row];break;
        case 1: title =   self.countryArr[row];break;
        case 2: title =   self.districtArr[row];break;
        default:break;
    }
    label.textAlignment = NSTextAlignmentCenter;
    label.text=title;
    
    if(component == 0){
        if(row == _index1){
            label.attributedText
            = [self pickerView:pickerView attributedTitleForRow:_index1 forComponent:component];
        }else{
            label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
        }
    }else if (component == 1){
        if(row == _index2){
            label.attributedText
            = [self pickerView:pickerView attributedTitleForRow:_index2 forComponent:component];
        }else{
            label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
        }
    }else if (component == 2){
        if(row == _index3){
            label.attributedText
            = [self pickerView:pickerView attributedTitleForRow:_index3 forComponent:component];
        }else{
            
            label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
        }
    }
    
    return label;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    
    return 40;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    UILabel *piketLabel =  (UILabel *)[pickerView viewForRow:row forComponent:component];
    piketLabel.textColor = UIColorHex(0xEEA72B);
    
    switch (component)
    {
        case 0:
        {
            self.index1 = row;
            self.index2 = 0;
            self.index3 = 0;
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            [self calculateFirstData];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            string1 = self.provinceArr[row];
            string2 = self.countryArr[self.index2];
            string3 = self.districtArr[self.index3];
            _homeAddStrID = self.districtIDArr[self.index3];
        }
            break;
            
        case 1:
        {
            self.index2 = row;
            self.index3 = 0;
            //            [self calculateData];
            [self calculateFirstData];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [pickerView reloadComponent:2];
             string2 = self.countryArr[row];
            string3 = self.districtArr[self.index3];
            _homeAddStrID = self.districtIDArr[self.index3];
        }
            break;
        case 2:
            self.index3 = row;
            string3 = self.districtArr[row];
            _homeAddStrID = self.districtIDArr[self.index3];
            break;
        default:break;
    }
    
    _homeAddStr = [NSString stringWithFormat:@"%@-%@-%@",string1,string2,string3];
     [shiquBut setTitle:[NSString stringWithFormat:@"%@-%@-%@",string1,string2,string3] forState:UIControlStateNormal];
}
- (void)configurePickerView:(UIPickerView *)pickerView
{
    pickerView.showsSelectionIndicator = YES;
}
- (void)preserveButOnclick:(UIButton *)sender{
    NSString * string = [NSString stringWithFormat:@"%@ %@",_homeAddStr,xiangxiTextView.text];
    if (kStringIsEmpty(string)) {
        
        [self showBottomMessag:@"请设置您的家庭住址"];
        
    }else{
        
        self.homeAddressBlcok(string,xiangxiTextView.text,_homeAddStrID);
        [self goBack];
    }
    
}

- (void)AddressJsonRequest{
    
    [[DDNetworkManagerDate makeUrl_sendsms_with_base_allRegion] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"====>>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            
            NSMutableArray *dataArr = [responseObject objectForKey:@"data"];
            
            if (dataArr.count > 0 && dataArr) {
                
                self.addressArr = dataArr;
                
                [self calculateFirstData];
                
                [self HomeAddressViewBuild];
            }

        }
    } failure:^(id errorObject) {
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
